package com.app.aipass.activity.order;

import android.app.Application;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableArrayList;
import androidx.databinding.ObservableList;

import com.app.aipass.BR;
import com.app.aipass.R;
import com.app.aipass.app.AppApplication;
import com.app.aipass.data.DemoRepository;
import com.app.aipass.entity.TransactionPlanEntity;
import com.app.aipass.http.response.ApiException;
import com.app.aipass.utils.TextUtil;

import java.util.HashMap;
import java.util.List;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.observers.DisposableObserver;
import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent;
import me.goldze.mvvmhabit.http.BaseResponse;
import me.goldze.mvvmhabit.http.ResponseThrowable;
import me.goldze.mvvmhabit.utils.RxUtils;
import me.goldze.mvvmhabit.utils.ToastUtils;
import me.tatarka.bindingcollectionadapter2.ItemBinding;

/**
 * @author: woking
 * @date: 2021/6/7
 * @description：
 */
public class OrderRecordTabViewModel extends BaseViewModel<DemoRepository> {
    private int page = 1;

    public SingleLiveEvent<OrderRecordTabItemViewModel> deleteItemLiveData = new SingleLiveEvent<>();
    //封装一个界面发生改变的观察者
    public UIChangeObservable uc = new UIChangeObservable();
    public SingleLiveEvent<Integer> type = new SingleLiveEvent<>();
    public SingleLiveEvent<Boolean> isOrder = new SingleLiveEvent<>();
    public class UIChangeObservable {
        //下拉刷新完成
        public SingleLiveEvent finishRefreshing = new SingleLiveEvent<>();
        //上拉加载完成
        public SingleLiveEvent finishLoadmore = new SingleLiveEvent<>();
    }

    public OrderRecordTabViewModel(@NonNull Application application, DemoRepository repository) {
        super(application, repository);
    }

    //给RecyclerView添加ObservableList
    public ObservableList<OrderRecordTabItemViewModel> observableList = new ObservableArrayList<>();
    //给RecyclerView添加ItemBinding
    public ItemBinding<OrderRecordTabItemViewModel> itemBinding = ItemBinding.of(BR.viewModel, R.layout.item_order_record_tab_item);

    //下拉刷新
    public BindingCommand onRefreshCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            requestNetWork(false);
        }
    });

    public void onRefresh()
    {
        requestNetWork(false);
    }

    public void onLoadMore()
    {
        requestNetWork(true);
    }

    //上拉加载
    public BindingCommand onLoadMoreCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            onLoadMore();
        }
    });

    /**
     * 网络请求方法，在ViewModel中调用Model层，通过Okhttp+Retrofit+RxJava发起请求
     */
    public void requestNetWork(boolean isLoadMore) {
        if(isOrder.getValue())
        {
            orderList(isLoadMore);
        }
        else
        {
            orderGuaDanList(isLoadMore);
        }
    }

    public void orderList(boolean isLoadMore)
    {
        //可以调用addSubscribe()添加Disposable，请求与View周期同步
        if(!isLoadMore)
        {
            page = 1;
        }

        HashMap<String, Object> map = new HashMap<>();
        map.put("lang","zh-cn");
        map.put("page",page+"");

        String status = null;
        if(type.getValue() != 0)
        {
//            map.put("status",(type.getValue() - 1));
            status = (type.getValue() - 1) + "";
        }

        model.otcBuyLists(status,page+"")
                .compose(RxUtils.schedulersTransformer()) //线程调度
                .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                .doOnSubscribe(this)//请求与ViewModel周期同步
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
//                        showDialog("正在请求...");
                    }
                })
                .subscribe(new DisposableObserver<BaseResponse<List<TransactionPlanEntity>>>() {
                    @Override
                    public void onNext(BaseResponse<List<TransactionPlanEntity>> response) {
//                        Log.e("TAG","============orderList=====onNext========");
                        if(!isLoadMore)
                        {
                            //清除列表
                            observableList.clear();
                        }
                        if(null != response && null != response.getData() && response.getData().size() > 0)
                        {
                            for (TransactionPlanEntity entity : response.getData()) {
                                entity.isOrder = true;
                                OrderRecordTabItemViewModel itemViewModel = new OrderRecordTabItemViewModel(OrderRecordTabViewModel.this, entity);
                                //双向绑定动态添加Item
                                observableList.add(itemViewModel);
                            }
                            if(response != null && null != response.meta && null != response.meta.pagination)
                            {
                                page = response.meta.pagination.current_page;
                                page++;
                            }
                        }
                    }
                    @Override
                    public void onError(Throwable throwable) {
                        Log.e("TAG","============orderList=====onError========"+throwable.getMessage());
                        if(!isLoadMore)
                        {
                            //请求刷新完成收回
                            uc.finishRefreshing.call();
                        }
                        else
                        {
                            uc.finishLoadmore.call();
                        }
//                        if (throwable instanceof ResponseThrowable) {
//                            ToastUtils.showShort(((ResponseThrowable) throwable).message);
//                        }

                        if (throwable instanceof ResponseThrowable) {
                            String msg = ApiException.getShowmessage(((ResponseThrowable) throwable).errorBody);
                            ToastUtils.showShortSafe(msg);

                            int code = ((ResponseThrowable) throwable).code;
                            if((!TextUtil.isEmpty(msg) && msg.contains("被禁")) || code == 403)
                            {
                                if(TextUtil.isEmpty(AppApplication.userJinYongMsg))
                                {
                                    AppApplication.userJinYongMsg = msg;
                                }
                                if(observableList.size() > 0)
                                {
                                    //清除列表
                                    observableList.clear();
                                    page = 1;
                                }
                            }
                            else
                            {
                                if(!TextUtil.isEmpty(AppApplication.userJinYongMsg))
                                {
                                    AppApplication.userJinYongMsg = "";
                                }
                            }
                        }
                    }
                    @Override
                    public void onComplete() {
//                        Log.e("TAG",isLoadMore+"============orderList=====onComplete========");
                        if(!isLoadMore)
                        {
                            //请求刷新完成收回
                            uc.finishRefreshing.call();
                        }
                        else
                        {
                            uc.finishLoadmore.call();
                        }
                    }
                });
    }
//    public void orderList2(boolean isLoadMore)
//    {
//        //可以调用addSubscribe()添加Disposable，请求与View周期同步
//        if(!isLoadMore)
//        {
//            page = 1;
//        }
//        else {
//            page++;
//        }
//        HashMap<String, Object> map = new HashMap<>();
//        map.put("lang","zh-cn");
//        map.put("page",page+"");
//        if(type.getValue() != 0)
//        {
//            map.put("status",(type.getValue() - 1));
//        }
//
//        model.orderList(map)
//                .compose(RxUtils.schedulersTransformer()) //线程调度
//                .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
//                .doOnSubscribe(this)//请求与ViewModel周期同步
//                .doOnSubscribe(new Consumer<Disposable>() {
//                    @Override
//                    public void accept(Disposable disposable) throws Exception {
////                        showDialog("正在请求...");
//                    }
//                })
//                .subscribe(new DisposableObserver<BaseResponse<OrderListEntity>>() {
//                    @Override
//                    public void onNext(BaseResponse<OrderListEntity> response) {
//                        Log.e("TAG","============orderList=====onNext========"+response.getData().list.current_page);
//                        if(!isLoadMore)
//                        {
//                            //清除列表
//                            observableList.clear();
//                        }
//                        //请求成功
//                        if (response.getCode() == 200) {
////                            for (DemoEntity.ItemsEntity entity : response.getResult().getItems()) {
////                                OrderRecordTabItemViewModel itemViewModel = new OrderRecordTabItemViewModel(OrderRecordTabViewModel.this, entity);
////                                //双向绑定动态添加Item
////                                observableList.add(itemViewModel);
////                            }
//                        } else {
//                            //code错误时也可以定义Observable回调到View层去处理
//                            ToastUtils.showShort("数据错误");
//                        }
//                    }
//                    @Override
//                    public void onError(Throwable throwable) {
//                        Log.e("TAG","============orderList=====onError========");
//                        //请求刷新完成收回
//                        uc.finishRefreshing.call();
//                        if (throwable instanceof ResponseThrowable) {
//                            ToastUtils.showShort(((ResponseThrowable) throwable).message);
//                        }
//                    }
//                    @Override
//                    public void onComplete() {
//                        Log.e("TAG",isLoadMore+"============orderList=====onComplete========");
//                        if(!isLoadMore)
//                        {
//                            //请求刷新完成收回
//                            uc.finishRefreshing.call();
//                        }
//                        else
//                        {
//                            uc.finishLoadmore.call();
//                        }
//                    }
//                });
//    }
    public void orderGuaDanList(boolean isLoadMore)
    {
        //可以调用addSubscribe()添加Disposable，请求与View周期同步
        if(!isLoadMore)
        {
            page = 1;
        }
//        else {
//            page++;
//        }
//        HashMap<String, Object> map = new HashMap<>();
//        map.put("lang","zh-cn");
//        map.put("page",page+"");
        String status = null;
        if(type.getValue() != 0)
        {
//            map.put("status",(type.getValue() - 1));
            status = (type.getValue() - 1) + "";
        }
        model.otcPlanLists(status,"orders",page+"")
                .compose(RxUtils.schedulersTransformer()) //线程调度
                .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                .doOnSubscribe(this)//请求与ViewModel周期同步
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
//                        showDialog("正在请求...");
                    }
                })
                .subscribe(new DisposableObserver<BaseResponse<List<TransactionPlanEntity>>>() {
                    @Override
                    public void onNext(BaseResponse<List<TransactionPlanEntity>> response) {
                        Log.e("TAG","============orderGuaDanList=====onNext========");
                        if(!isLoadMore)
                        {
                            //清除列表
                            observableList.clear();
                        }
                        if(null != response && null != response.getData() && response.getData().size() > 0)
                        {
                            for (TransactionPlanEntity entity : response.getData())
                            {
                                if(entity.order_status_no_pay != 1)
                                {
                                    entity.isOrder = false;
                                    OrderRecordTabItemViewModel itemViewModel = new OrderRecordTabItemViewModel(OrderRecordTabViewModel.this, entity);
                                    //双向绑定动态添加Item
                                    observableList.add(itemViewModel);
                                }
                            }
                            if(response != null && null != response.meta && null != response.meta.pagination)
                            {
                                page = response.meta.pagination.current_page;
                                page++;
                            }
                        }
                    }
                    @Override
                    public void onError(Throwable throwable) {
                        Log.e("TAG","============orderGuaDanList=====onError========"+throwable.getMessage());
                        if(!isLoadMore)
                        {
                            //请求刷新完成收回
                            uc.finishRefreshing.call();
                        }
                        else
                        {
                            uc.finishLoadmore.call();
                        }
//                        if (throwable instanceof ResponseThrowable) {
//                            ToastUtils.showShort(((ResponseThrowable) throwable).message);
//                        }
                        if (throwable instanceof ResponseThrowable) {
                            String msg = ApiException.getShowmessage(((ResponseThrowable) throwable).errorBody);
                            ToastUtils.showShortSafe(msg);

                            int code = ((ResponseThrowable) throwable).code;
                            if((!TextUtil.isEmpty(msg) && msg.contains("被禁")) || code == 403)
                            {
                                if(TextUtil.isEmpty(AppApplication.userJinYongMsg))
                                {
                                    AppApplication.userJinYongMsg = msg;
                                }
                                if(observableList.size() > 0)
                                {
                                    //清除列表
                                    observableList.clear();
                                    page = 1;
                                }
                            }
                            else
                            {
                                if(!TextUtil.isEmpty(AppApplication.userJinYongMsg))
                                {
                                    AppApplication.userJinYongMsg = "";
                                }
                            }
                        }
                    }
                    @Override
                    public void onComplete() {
                        Log.e("TAG",isLoadMore+"============orderGuaDanList=====onComplete========");
                        if(!isLoadMore)
                        {
                            //请求刷新完成收回
                            uc.finishRefreshing.call();
                        }
                        else
                        {
                            uc.finishLoadmore.call();
                        }

                        if(!TextUtil.isEmpty(AppApplication.userJinYongMsg))
                        {
                            AppApplication.userJinYongMsg = "";
                        }
                    }
                });
    }
//    public void orderGuaDanList2(boolean isLoadMore)
//    {
//        //可以调用addSubscribe()添加Disposable，请求与View周期同步
//        if(!isLoadMore)
//        {
//            page = 1;
//        }
//        else {
//            page++;
//        }
//        HashMap<String, Object> map = new HashMap<>();
//        map.put("lang","zh-cn");
//        map.put("page",page+"");
//        if(type.getValue() != 0)
//        {
//            map.put("status",(type.getValue() - 1));
//        }
//        model.orderGuaDanList(map)
//                .compose(RxUtils.schedulersTransformer()) //线程调度
//                .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
//                .doOnSubscribe(this)//请求与ViewModel周期同步
//                .doOnSubscribe(new Consumer<Disposable>() {
//                    @Override
//                    public void accept(Disposable disposable) throws Exception {
////                        showDialog("正在请求...");
//                    }
//                })
//                .subscribe(new DisposableObserver<BaseResponse<OrderListEntity>>() {
//                    @Override
//                    public void onNext(BaseResponse<OrderListEntity> response) {
//                        Log.e("TAG","============orderList=====onNext========"+response.getData().list.current_page);
//                        if(!isLoadMore)
//                        {
//                            //清除列表
//                            observableList.clear();
//                        }
//                        //请求成功
//                        if (response.getCode() == 200) {
////                            for (DemoEntity.ItemsEntity entity : response.getResult().getItems()) {
////                                OrderRecordTabItemViewModel itemViewModel = new OrderRecordTabItemViewModel(OrderRecordTabViewModel.this, entity);
////                                //双向绑定动态添加Item
////                                observableList.add(itemViewModel);
////                            }
//                        } else {
//                            //code错误时也可以定义Observable回调到View层去处理
//                            ToastUtils.showShort("数据错误");
//                        }
//                    }
//                    @Override
//                    public void onError(Throwable throwable) {
//                        Log.e("TAG","============orderList=====onError========");
//                        //请求刷新完成收回
//                        uc.finishRefreshing.call();
//                        if (throwable instanceof ResponseThrowable) {
//                            ToastUtils.showShort(((ResponseThrowable) throwable).message);
//                        }
//                    }
//                    @Override
//                    public void onComplete() {
//                        Log.e("TAG",isLoadMore+"============orderList=====onComplete========");
//                        if(!isLoadMore)
//                        {
//                            //请求刷新完成收回
//                            uc.finishRefreshing.call();
//                        }
//                        else
//                        {
//                            uc.finishLoadmore.call();
//                        }
//                    }
//                });
//    }
    /**
     * 删除条目
     *
     * @param netWorkItemViewModel
     */
    public void deleteItem(OrderRecordTabItemViewModel netWorkItemViewModel) {
        //点击确定，在 observableList 绑定中删除，界面立即刷新
        observableList.remove(netWorkItemViewModel);
    }

    /**
     * 获取条目下标
     *
     * @param netWorkItemViewModel
     * @return
     */
    public int getItemPosition(OrderRecordTabItemViewModel netWorkItemViewModel) {
        return observableList.indexOf(netWorkItemViewModel);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}